package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.task.config.MqConst;
import com.atguigu.gmall.task.service.RabbitService;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author: 李旭
 * @create: 2021-07-03 15:20
 **/
@Service
@Slf4j
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;//只写接口 不写实现类
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;//只写接口 不写实现类
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;//只写接口 不写实现类
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    //查询一级分类集合
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    //查询二级分类集合
    @Override
    public List<BaseCategory2> getCategory2(Long categoryId1) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
          .eq("category1_id",categoryId1));
    }
    //查询三级分类集合
    @Override
    public List<BaseCategory3> getCategory3(Long categoryId2) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id",categoryId2));
    }
    //查询平台属性及值集合  入参 ： 一二三级分类Id
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);
    }
    //添加平台属性及值 二张表
    @Override
    @Transactional(rollbackFor = FileNotFoundException.class) //第一个问题：此事务注解能回滚所有异常 （不能 只能RuntimeException )  FileNotFound  1/0
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //1:平台属性表 1
        baseAttrInfoMapper.insert(baseAttrInfo);
        //2:平台属性值表 N
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if(!CollectionUtils.isEmpty(attrValueList)){
            attrValueList.forEach(baseAttrValue -> {
                //外键
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            });
        }

    }

    //品牌分页查询
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page<BaseTrademark>(page,limit),
                null);
    }

    //品牌名称
    @Override
    public void baseTrademarkSave(BaseTrademark baseTrademark) {
        baseTrademarkMapper.insert(baseTrademark);
    }

    //SPU分页列表查询
    @Override
    public IPage spuPageList(Integer page, Integer limit, Long category3Id) {
        return spuInfoMapper.selectPage(new Page(page,limit),
                new QueryWrapper<SpuInfo>().eq("category3_id",category3Id));
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }
    //添加SPU
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1:spu_info    1条数据   返回spu_info表的主键
        spuInfoMapper.insert(spuInfo);
        //2:spu_image   N条数据
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        spuImageList.forEach(spuImage -> {
            //外键
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        //3:spu_sale_atte N条数据
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        spuSaleAttrList.forEach(spuSaleAttr -> {
            //外键
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4:spu_sale_atte_value N条数据
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                //外键
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                //销售属性名称
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });

    }


    //根据spuId 查询所有图片集合
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>()
          .eq("spu_id",spuId));
    }
    //根据spuId 获取销售属性
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {

        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }
    //添加SKU
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //1:sku_info  1
        skuInfoMapper.insert(skuInfo);
        //2:sku_image  N
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> {
            //外键
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //3:sku_attr_value N
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //4:sku_sale_attr_value N
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            //外键
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });

    }
    //SKU分页查询
    @Override
    public IPage skuPageList(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<SkuInfo>(page,limit),null);
    }

    @Autowired
    private RabbitService rabbitService;

    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ONSALE);
        skuInfoMapper.updateById(skuInfo);
        //发消息 通知 ES
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_UPPER,skuId);

    }
    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();//Mybatis-plus
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.CANCELSALE);
        skuInfoMapper.updateById(skuInfo);
        // update sku_info set is_sale = 0 where id = ?
        //发消息 通知 ES
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;//解决分布式锁

    // Aop 前置  后置 异常 返回值   环绕
    //1：查询SkuInfo 根据skuId
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //1:先查询Redis    sku:1:info
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if(skuInfo == null){
            //缓存的击穿问题  上锁
            String cacheLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLock);
            //上锁
            //参数1：过期 过多久之后不再获取锁了
            //参数2：获取到锁之后 锁的过期时间
            //参数3：时间单位
            try {
                boolean b = lock.tryLock(1, 2, TimeUnit.SECONDS);
                if(b){
                    try {
                        //获取到了锁
                        skuInfo = skuInfoMapper.selectById(skuId);
                        if(null != skuInfo){
                            //不为空 获取图片集合
                            skuInfo.setSkuImageList(
                                    skuImageMapper.selectList(new QueryWrapper<SkuImage>().
                                            eq("sku_id",skuId)));
                            //保存缓存一份
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                   RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300),
                                    TimeUnit.SECONDS);

                        }else{
                            // 缓存的穿透问题
                            skuInfo = new SkuInfo();
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,5,TimeUnit.MINUTES);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        //释放锁
                        lock.unlock();
                    }
                }else{
                    //未获取锁  直接获取缓存中数据
                    TimeUnit.SECONDS.sleep(1);
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //直接返回
        return skuInfo;
    }

/*    @Override
    public SkuInfo getSkuInfo(Long skuId) {
         //1:先查询Redis
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if(null == skuInfo){
            // 第三大问题：缓存击穿  上锁  防止100万并了直接访问DB  造成DB宕机  过期不候的锁
            String uuid = UUID.randomUUID().toString();
            String cacheLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(cacheLock, uuid, 3, TimeUnit.SECONDS);
            if(aBoolean){
                //3:无数据 查询DB
                skuInfo = skuInfoMapper.selectById(skuId);
                if(null != skuInfo){
                    skuInfo.setSkuImageList(
                            skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id",skuId)));
                    //4:保存缓存一份  new Random().nextInt(300)  解决缓存雪崩问题
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,
                            RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLock), uuid);
                }else{
                    //缓存穿透
                    skuInfo =  new SkuInfo();//空结果 ： 对象是有的 对象中没有属性值
                    //4:保存缓存一份
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,5, TimeUnit.MINUTES);
                }
            }
        }
        //5:直接返回
        return skuInfo;
    }*/
/*    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(null != skuInfo){
            skuInfo.setSkuImageList(
                    skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id",skuId)));
        }
        return skuInfo;
    }*/
    //2：查询 分类视图  条件：三级分类的ID    sku:category3Id:info
    @Override
    @GmallCache(prefix="getBaseCagegoryView",suffix = "view")
    public BaseCategoryView getBaseCagegoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    //查询  select price from sku_info where id = ?
    @Override
    public BigDecimal getPrice(Long skuId) {
        QueryWrapper queryWrapper = new QueryWrapper<SkuInfo>();
        queryWrapper.select("price");
        queryWrapper.eq("id",skuId);
        SkuInfo skuInfo = skuInfoMapper.selectOne(queryWrapper);
        if(null != skuInfo){
            return skuInfo.getPrice();
        }
        return null;
    }
    //根据spuId,skuId 查询销售属性及属性值  集合  销售属性及值的红边框  SQL
    @Override
    @GmallCache(prefix="getSpuSaleAttrAndValue",suffix = "attr")
    public List<SpuSaleAttr> getSpuSaleAttrAndValue(Long spuId, Long skuId) {
        return spuSaleAttrMapper.getSpuSaleAttrAndValue(spuId,skuId);
    }
    //5:组合数据   返回值 Map  没有可使用的对象的时候 使用Map  无敌版对象  万能对象
    @Override
    @GmallCache(prefix="getSaleAttrValuesBySpu",suffix = "map")
    public Map getSaleAttrValuesBySpu(Long spuId) {//List<Map>
        List<Map> listMap = skuSaleAttrValueMapper.getSaleAttrValuesBySpu(spuId);
        //Map : values_id : 9|11|13   sku_id:10
        //Map : values_id : 9|12|13   sku_id:11
        //...
        Map result = new HashMap();
        listMap.forEach(map -> {
            result.put(map.get("values_id"),map.get("sku_id"));
        });
        return result;
    }
    //首页之所有需要一二三级分类  查询分类视图即可
    @Override
    public List<BaseCategoryView> getBaseCagegoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    ////:根据tmId 查询 base_trademark
    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }
    //根据skuId 查询base_attr_info（平台属性名） base_attr_value（平台属性值表）  sku_attr_value (关联表）
    @Override
    public List<Map> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
}
